#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>

#include "body.h"

static unsigned int bcount;

static double getDistance(Body *b1, Body *b2)
{
	double dx, dy;
	dx = abs(b1->posx - b2->posx);
	dy = abs(b1->posy - b2->posy);

	return sqrt(dx*dx + dy*dy);
}

Body::Body()
{
	//std::cout << "*";

	bcount++;
	this->id = bcount;

	this->dt = 1;
	this->mass = 1;
	this->posx = bcount;
	this->posy = bcount;
	this->velx = 0;
	this->vely = 0;
}

Body::~Body()
{
	//std::cout << "#";
	bcount--;
}

void
Body::calcNewForce(Body *body)
{
	double m1,m2,r,r0x,r0y;
		
	r = getDistance(this, body);
	if (r == 0.0) return;

	r0x = this->posx - body->posx;
	r0y = this->posy - body->posy;
	
	m1 = this->mass;
	m2 = body->mass;

	this->fx += (-1*GRAVCONST)*(((m1 * m2)/(r*r))*r0x);
	this->fy += (-1*GRAVCONST)*(((m1 * m2)/(r*r))*r0y);
}

void
Body::calcNewPos(void)
{
	double ax,ay, vx,vy, sx,sy;

	ax = this->fx / this->mass;
	ay = this->fy / this->mass;

	vx = this->velx + (ax * this->dt);
	vy = this->vely + (ay * this->dt);

	this->velx = vx;
	this->vely = vy;

	sx = vx * this->dt;
	sy = vy * this->dt;
	
	this->posx += sx;
	this->posy += sy;
}

int
Body::getBodyCount(void)
{
	return bcount;
}

void
Body::setMass(double mass)
{
	this->mass = mass;
}

void
Body::setDt(double dt)
{
	this->dt = dt;
}

void
Body::setPos(double x, double y)
{
	this->posx = x;
	this->posy = y;
}

